package com.ship.dispatch.bpm.task.listener;


import com.ship.common.core.utils.StringUtil;
import com.ship.dispatch.bpm.utils.ApplicationContextUtil;
import com.ship.dispatch.bpm.utils.CalculateDateUtil;
import com.ship.dispatch.bpm.vo.dto.RuntimeTaskDto;
import com.ship.dispatch.service.fob.FobService;
import com.ship.dispatch.service.fob.impl.FobServiceImpl;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component("taskAssignerListener")
public class TaskAssignerListener implements TaskListener {

    FobService fobService;
    @Override
    public void notify(DelegateTask delegateTask) {
        // 参数
        Map<String, Object> variables = delegateTask.getVariables();
        String userId = variables.get("assigeners").toString();
        // 预计装载时间
        fobService = ApplicationContextUtil.getBean(FobServiceImpl.class);
        String expectedLoadingDateKey = fobService.getPlanDateByNodeKey(delegateTask.getCategory());
        String expectedLoadingDate = null;
        if(variables.containsKey(expectedLoadingDateKey)){
            Object tempDate = variables.get(expectedLoadingDateKey)!=null?variables.get(expectedLoadingDateKey):null;
            if(tempDate instanceof Date){
                expectedLoadingDate = CalculateDateUtil.pasrseDate((Date) tempDate);
            }else{
                expectedLoadingDate = tempDate!=null?tempDate.toString():null;
            }

        }
        RuntimeTaskDto runtimeTaskDto = fobService.getAssigenersAndSetEndDate(delegateTask.getProcessInstanceId(),delegateTask.getId(),variables.get("businessKey").toString(),delegateTask.getCategory(),expectedLoadingDate,delegateTask.getName(),userId);
        if(runtimeTaskDto!=null && !StringUtil.isEmpty(runtimeTaskDto.getAddAssigeners())){
            userId = userId+","+runtimeTaskDto.getAddAssigeners();
        }
        List<String> ids = Arrays.stream(userId.split(",")).collect(Collectors.toList());
        HashSet<String> set = new HashSet<>(ids);
        delegateTask.addCandidateUsers(set);
        if(runtimeTaskDto.getExpectedLoadingDate() != null){
            delegateTask.setDueDate(runtimeTaskDto.getExpectedLoadingDate());
        }
    }
}
